import React, { useEffect, useState, Fragment } from 'react'
import { Button, message, Table } from 'antd'
import { withRouter } from 'react-router-dom'
import moment from 'moment'
import { getChannelList } from '../../../request/product'
import ENUMS from '../../../constants'

function Channel(props) {
  const [isLoading, setIsLoading] = useState(false)
  const [channelList, setChannelList] = useState([])

  useEffect(() => {
    getList().catch(e => console.log(e.message))
  }, [])

  const getList = async(p) => {
    setIsLoading(true)
    const { code, message: errMsg, data } = await getChannelList()
    setIsLoading(false)
    if (code) {
      message.error(errMsg)
      return false
    }
    setChannelList(data)
  }

  const columns = [
    {
      title: '序号',
      dataIndex: 'id',
      align: 'center',
      width: '100px',
      render: (text, record, index) => (index + 1)
    },
    {
      title: '产品名称',
      dataIndex: 'name'
    },
    {
      title: '产品编码',
      dataIndex: 'code'
    },
    {
      title: '运营商',
      dataIndex: 'isp',
      render: text => <span>{ENUMS.ISP[text] || '-'}</span>
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      render: text => text ? moment(text * 1000).format('YYYY-MM-DD HH:mm:ss') : '-'
    },
    {
      title: '库存',
      dataIndex: 'stock'
    },
    {
      title: '操作',
      width: 200,
      align: 'center',
      render: (text, record) => (
        <Fragment>
          <Button
            size="small"
            style={{ marginRight: '10px' }}
            onClick={() => props.history.push(`/product/channel/edit/${record.id}`)}
          >
            编辑
          </Button>
        </Fragment>
      )
    }
  ]
  return (
    <div className="package">
      <div className="menu">
        <Button type="primary" onClick={() => {
          props.history.push('/product/channel/add')
        }}>新增产品渠道</Button>
      </div>
      <Table
        loading={isLoading}
        rowKey={row => row.id}
        columns={columns}
        pagination={false}
        dataSource={channelList}
      />
    </div>
  )
}

export default withRouter(Channel)
